

//==================== 1. 补充缺失的 updateExportScopeInfo 函数 ====================
function updateExportScopeInfo() {
    const scopeInfo = document.getElementById('exportScopeInfo');
    const folderId = document.getElementById('exportFolderId').value;
    const cardIds = document.getElementById('exportCardIds').value;
    
    if (!scopeInfo) {
        console.warn('未找到 exportScopeInfo 元素');
        return;
    }
    
    if (folderId) {
        const folderName = getCurrentFolderName();
        scopeInfo.innerHTML = '<i class="fas fa-folder"></i> 导出整个名片夹: <strong>' + folderName + '</strong>';
    } else if (cardIds) {
        try {
            const ids = JSON.parse(cardIds);
            scopeInfo.innerHTML = '<i class="fas fa-file"></i> 导出选中的 <strong>' + ids.length + '</strong> 张名片';
        } catch (e) {
            scopeInfo.innerHTML = '<i class="fas fa-file"></i> 导出选中的名片';
        }
    } else {
        scopeInfo.innerHTML = '<i class="fas fa-info-circle"></i> 请先选择要导出的内容';
    }
}

// 获取当前文件夹名称的辅助函数
function getCurrentFolderName() {
    const activeFolder = document.querySelector('.card-folder.active');
    return activeFolder ? activeFolder.textContent.trim() : '未知文件夹';
}


//==================== 3. 增强打印功能 ====================
//修改打印函数，支持预览和样式控制
//修改原有的打印函数，添加权限检查
function printCards(cardIds, showPreview = false) {
    console.log('打印名片，IDs:', cardIds, '预览模式:', showPreview);
    
    // 🔧 修复：添加权限检查
    if (!checkPermissionBeforeAction('print', '打印名片')) {
        return;
    }
    
    // 如果没有指定cardIds，打印当前文件夹的所有名片
    if (!cardIds || cardIds.length === 0) {
        if (!currentFolder) {
            showMessage('请先选择一个名片夹或具体的名片', 'error');
            return;
        }
        // 获取当前文件夹的所有名片ID
        const currentCards = document.querySelectorAll('.card-item[data-id]');
        cardIds = Array.from(currentCards).map(card => parseInt(card.dataset.id));
    }
    
    if (cardIds.length === 0) {
        showMessage('没有可打印的名片', 'error');
        return;
    }
    
    showLoader();
    
    // 获取名片数据
    Promise.all(cardIds.map(cardId => getCardDataForPrint(cardId)))
        .then(cardsData => {
            hideLoader();
            cardsData = cardsData.filter(card => card !== null); // 过滤无效数据
            
            if (cardsData.length === 0) {
                showMessage('没有有效的名片数据可打印', 'error');
                return;
            }
            
            if (showPreview) {
                showPrintPreview(cardsData);
            } else {
                executePrint(cardsData);
            }
        })
        .catch(error => {
            hideLoader();
            console.error('获取打印数据失败:', error);
            showMessage('获取打印数据失败: ' + error.message, 'error');
        });
}

//获取单张名片的打印数据
async function getCardDataForPrint(cardId) {
 try {
     const response = await fetch('BusinessCardServlet?action=getCardById&cardId=' + cardId);
     if (!response.ok) {
         throw new Error('获取名片数据失败');
     }
     return await response.json();
 } catch (error) {
     console.error('获取名片' + cardId + '失败:', error);
     return null;
 }
}

//执行打印
//🔧 修复2：完全重写executePrint函数，强制居中大窗口
function executePrint(cardsData) {
    console.log('🖨️ 开始执行打印，名片数量:', cardsData.length);
    
    // 创建打印内容
    const printContent = generatePrintHTML(cardsData);
    
    // 🔧 获取屏幕信息
    const screen = window.screen;
    const screenWidth = screen.availWidth || screen.width;
    const screenHeight = screen.availHeight || screen.height;
    
    console.log('📱 屏幕尺寸:', screenWidth, 'x', screenHeight);
    
    // 🔧 计算理想窗口大小 - 占屏幕85%，最小1000x700
    const idealWidth = Math.max(1000, Math.floor(screenWidth * 0.85));
    const idealHeight = Math.max(700, Math.floor(screenHeight * 0.85));
    
    // 🔧 计算精确居中位置
    const leftPosition = Math.max(0, Math.floor((screenWidth - idealWidth) / 2));
    const topPosition = Math.max(0, Math.floor((screenHeight - idealHeight) / 2));
    
    console.log('🎯 计算的窗口参数:', {
        width: idealWidth,
        height: idealHeight,
        left: leftPosition,
        top: topPosition
    });
    
    // 🔧 使用多种方式尝试打开大窗口
    let printWindow = null;
    
    // 方法1：标准window.open
    const features = [
        `width=${idealWidth}`,
        `height=${idealHeight}`,
        `left=${leftPosition}`,
        `top=${topPosition}`,
        'resizable=yes',
        'scrollbars=yes',
        'status=yes',
        'menubar=yes',
        'toolbar=yes',
        'location=no',
        'directories=no'
    ].join(',');
    
    try {
        printWindow = window.open('about:blank', 'PrintWindow', features);
        
        if (!printWindow) {
            // 方法2：如果被阻止，尝试简化参数
            console.log('⚠️ 标准打开失败，尝试简化模式');
            printWindow = window.open('', '_blank', `width=${idealWidth},height=${idealHeight},resizable=yes`);
        }
        
        if (!printWindow) {
            // 方法3：最后尝试无参数打开
            console.log('⚠️ 简化模式失败，尝试基础模式');
            printWindow = window.open('', '_blank');
        }
        
        if (!printWindow) {
            throw new Error('浏览器阻止了弹出窗口');
        }
        
    } catch (error) {
        console.error('❌ 打开窗口失败:', error);
        showMessage('无法打开打印窗口，请检查浏览器弹窗设置', 'error');
        return;
    }
    
    // 🔧 设置窗口内容和属性
    try {
        // 设置标题
        printWindow.document.title = `名片打印预览 - ${cardsData.length}张名片`;
        
        // 写入内容
        printWindow.document.write(printContent);
        printWindow.document.close();
        
        // 🔧 强制调整窗口大小和位置（如果浏览器允许）
        setTimeout(() => {
            try {
                printWindow.focus();
                
                // 尝试强制设置窗口大小和位置
                if (printWindow.resizeTo && printWindow.moveTo) {
                    printWindow.resizeTo(idealWidth, idealHeight);
                    printWindow.moveTo(leftPosition, topPosition);
                    console.log('✅ 成功调整窗口大小和位置');
                } else {
                    console.log('⚠️ 浏览器不支持窗口大小调整');
                }
                
                // 🔧 延迟触发打印，确保内容完全加载
                setTimeout(() => {
                    if (printWindow && !printWindow.closed) {
                        printWindow.print();
                        console.log('🖨️ 打印对话框已启动');
                    }
                }, 1000); // 增加延迟确保内容渲染完成
                
            } catch (adjustError) {
                console.warn('⚠️ 窗口调整失败（可能被浏览器安全策略阻止）:', adjustError);
                
                // 即使调整失败，仍然尝试打印
                setTimeout(() => {
                    if (printWindow && !printWindow.closed) {
                        printWindow.print();
                    }
                }, 800);
            }
        }, 500);
        
        // 🔧 添加窗口关闭监听（打印完成后自动关闭）
        const checkWindowClosed = setInterval(() => {
            if (printWindow.closed) {
                clearInterval(checkWindowClosed);
                console.log('🔒 打印窗口已关闭');
            }
        }, 1000);
        
        // 🔧 5分钟后自动清理（防止内存泄漏）
        setTimeout(() => {
            if (checkWindowClosed) {
                clearInterval(checkWindowClosed);
            }
        }, 300000);
        
    } catch (contentError) {
        console.error('❌ 设置窗口内容失败:', contentError);
        showMessage('打印窗口内容加载失败', 'error');
        if (printWindow && !printWindow.closed) {
            printWindow.close();
        }
        return;
    }
    
    // 🔧 显示成功消息
    showMessage(`✅ 打印窗口已打开 (${idealWidth}×${idealHeight})`, 'success');
    
    // 🔧 添加打印提示
    setTimeout(() => {
        if (printWindow && !printWindow.closed) {
            console.log('💡 如果打印对话框未自动弹出，请在打印窗口中按 Ctrl+P');
        }
    }, 3000);
}

//显示打印预览
//重新设计 showPrintPreview 函数
function showPrintPreview(cardsData) {
    // 创建预览模态框
    const previewModal = document.createElement('div');
    previewModal.className = 'modal print-preview-modal';
    previewModal.style.display = 'block';
    previewModal.innerHTML = `
        <div class="modal-content print-preview-content" style="width: 95%; max-width: 1200px; max-height: 95vh;">
            <div class="modal-header">
                <h2><i class="fas fa-print"></i> 打印预览 (${cardsData.length}张名片)</h2>
                <span class="close">&times;</span>
            </div>
            
            <!-- 打印设置工具栏 -->
            <div class="print-settings-toolbar">
                <div class="print-settings-row">
                    <div class="print-setting-group">
                        <label for="previewCardsPerRow">每行名片数：</label>
                        <select id="previewCardsPerRow">
                            <option value="2">2张/行</option>
                            <option value="3">3张/行</option>
                            <option value="4" selected>4张/行</option>
                        </select>
                    </div>
                    <div class="print-setting-group">
                        <label for="previewPageSize">页面大小：</label>
                        <select id="previewPageSize">
                            <option value="A4" selected>A4</option>
                            <option value="A3">A3</option>
                            <option value="Letter">Letter</option>
                        </select>
                    </div>
                    <div class="print-setting-group">
                        <label for="previewOrientation">页面方向：</label>
                        <select id="previewOrientation">
                            <option value="portrait" selected>纵向</option>
                            <option value="landscape">横向</option>
                        </select>
                    </div>
                    <div class="print-setting-group">
                        <button type="button" class="btn btn-secondary btn-sm" id="refreshPreview">
                            <i class="fas fa-sync-alt"></i> 刷新预览
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 预览内容区域 -->
            <div class="cards-preview-container" id="previewContainer">
                ${generateEnhancedPreviewHTML(cardsData)}
            </div>
            
            <!-- 预览统计信息 -->
            <div class="preview-stats">
                <span><i class="fas fa-info-circle"></i> 总计：${cardsData.length} 张名片</span>
                <span><i class="fas fa-file-alt"></i> 预计页数：${Math.ceil(cardsData.length / 20)} 页</span>
                <span><i class="fas fa-clock"></i> 预览生成时间：${new Date().toLocaleString()}</span>
            </div>
            
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" id="closePrintPreview">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="btn btn-info" id="printSettings">
                    <i class="fas fa-cog"></i> 打印设置
                </button>
                <button type="button" class="btn btn-primary print-enhanced-btn" id="executePrintNow">
                    <i class="fas fa-print"></i> 确认打印
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(previewModal);
    
    // 绑定事件
    bindPreviewEvents(previewModal, cardsData);
}


//生成增强的预览HTML
function generateEnhancedPreviewHTML(cardsData, cardsPerRow = 4) {
    let html = '';
    const totalPages = Math.ceil(cardsData.length / (cardsPerRow * 5)); // 每页最多5行
    
    for (let page = 0; page < totalPages; page++) {
        const startIndex = page * cardsPerRow * 5;
        const endIndex = Math.min(startIndex + cardsPerRow * 5, cardsData.length);
        const pageCards = cardsData.slice(startIndex, endIndex);
        
        html += `
            <div class="preview-page" data-page="${page + 1}">
                <div class="preview-page-header">
                    <div class="page-title">名片册系统 - 打印输出</div>
                    <div class="page-info">第 ${page + 1} 页，共 ${totalPages} 页</div>
                    <div class="print-date">${new Date().toLocaleDateString()}</div>
                </div>
                
                <div class="preview-cards-grid" data-cards-per-row="${cardsPerRow}">
                    ${generatePageCardsHTML(pageCards, cardsPerRow)}
                </div>
                
                <div class="preview-page-footer">
                    <div class="footer-left">由名片册系统生成</div>
                    <div class="footer-center">共 ${cardsData.length} 张名片</div>
                    <div class="footer-right">页码：${page + 1}/${totalPages}</div>
                </div>
            </div>
        `;
        
        if (page < totalPages - 1) {
            html += '<div class="page-separator"></div>';
        }
    }
    
    return html;
}

//生成单页名片HTML
function generatePageCardsHTML(pageCards, cardsPerRow) {
    let html = '';
    
    // 按行分组
    for (let i = 0; i < pageCards.length; i += cardsPerRow) {
        const rowCards = pageCards.slice(i, i + cardsPerRow);
        
        html += '<div class="preview-cards-row">';
        
        rowCards.forEach(card => {
            html += generateEnhancedCardHTML(card);
        });
        
        // 填充空位
        for (let j = rowCards.length; j < cardsPerRow; j++) {
            html += '<div class="preview-business-card empty-placeholder"></div>';
        }
        
        html += '</div>';
    }
    
    return html;
}


//生成增强的单张名片HTML
function generateEnhancedCardHTML(card) {
    return `
        <div class="preview-business-card">
            <div class="card-decoration-top"></div>
            
            <div class="preview-card-header">
                <div class="preview-card-name">${card.name || ''}</div>
                <div class="preview-card-title">${card.title || ''}</div>
            </div>
            
            <div class="card-divider"></div>
            
            <div class="preview-card-company">
                <i class="company-icon">🏢</i>
                <strong>${card.organization || ''}</strong>
            </div>
            
            <div class="preview-card-contact">
                <div class="preview-contact-item">
                    <i class="contact-icon phone-icon">📞</i>
                    <span class="contact-text">${card.phone || ''}</span>
                </div>
                <div class="preview-contact-item">
                    <i class="contact-icon email-icon">✉️</i>
                    <span class="contact-text">${card.email || ''}</span>
                </div>
                <div class="preview-contact-item">
                    <i class="contact-icon address-icon">📍</i>
                    <span class="contact-text">${card.address || ''}</span>
                </div>
            </div>
            
            <div class="preview-card-gender">
                <span class="gender-badge">${card.gender || ''}</span>
            </div>
            
            <div class="card-decoration-bottom"></div>
            
            <!-- 名片编号 -->
            <div class="card-number">#${card.cardId || ''}</div>
        </div>
    `;
}

// 绑定预览事件
function bindPreviewEvents(modal, cardsData) {
    // 关闭按钮
    modal.querySelector('.close').onclick = () => {
        document.body.removeChild(modal);
    };
    
    modal.querySelector('#closePrintPreview').onclick = () => {
        document.body.removeChild(modal);
    };
    
    // 确认打印按钮
    modal.querySelector('#executePrintNow').onclick = () => {
        document.body.removeChild(modal);
        executePrint(cardsData);
    };
    
    // 刷新预览按钮
    modal.querySelector('#refreshPreview').onclick = () => {
        const cardsPerRow = parseInt(modal.querySelector('#previewCardsPerRow').value);
        const container = modal.querySelector('#previewContainer');
        container.innerHTML = generateEnhancedPreviewHTML(cardsData, cardsPerRow);
        
        showMessage('预览已刷新', 'success');
    };
    
    // 预览设置变更
    modal.querySelector('#previewCardsPerRow').onchange = function() {
        const container = modal.querySelector('#previewContainer');
        container.innerHTML = generateEnhancedPreviewHTML(cardsData, parseInt(this.value));
    };
    
    // 打印设置按钮
    modal.querySelector('#printSettings').onclick = () => {
        showPrintSettingsDialog();
    };
    
    // 页面方向变更
    modal.querySelector('#previewOrientation').onchange = function() {
        const container = modal.querySelector('#previewContainer');
        container.className = 'cards-preview-container ' + this.value;
    };
}

// 显示打印设置对话框
function showPrintSettingsDialog() {
    const settingsHtml = `
        <div class="print-status info">
            <i class="fas fa-cog"></i>
            <div>
                <strong>打印提示：</strong><br>
                • 建议使用高质量打印模式<br>
                • 选择合适的纸张尺寸（A4推荐）<br>
                • 可在浏览器打印对话框中进一步调整设置
            </div>
        </div>
    `;
    
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = settingsHtml;
    tempDiv.style.position = 'fixed';
    tempDiv.style.top = '50%';
    tempDiv.style.left = '50%';
    tempDiv.style.transform = 'translate(-50%, -50%)';
    tempDiv.style.zIndex = '3000';
    tempDiv.style.backgroundColor = 'white';
    tempDiv.style.padding = '20px';
    tempDiv.style.borderRadius = '8px';
    tempDiv.style.boxShadow = '0 10px 30px rgba(0,0,0,0.3)';
    tempDiv.style.maxWidth = '400px';
    
    document.body.appendChild(tempDiv);
    
    setTimeout(() => {
        if (document.body.contains(tempDiv)) {
            document.body.removeChild(tempDiv);
        }
    }, 3000);
}



//生成完整的打印HTML
function generatePrintHTML(cardsData, isPreview = false) {
 return `
     <!DOCTYPE html>
     <html>
     <head>
         <meta charset="UTF-8">
         <title>名片打印 - ${cardsData.length}张</title>
         <style>
             ${getPrintCSS()}
         </style>
     </head>
     <body>
         ${generateCardsPrintHTML(cardsData)}
         ${isPreview ? '' : '<script>window.onload = () => { setTimeout(() => window.print(), 100); };</script>'}
     </body>
     </html>
 `;
}

//生成名片打印HTML内容
function generateCardsPrintHTML(cardsData) {
 let html = '';
 
 // 每4张名片一行，最多5行
 for (let i = 0; i < cardsData.length; i += 4) {
     const rowCards = cardsData.slice(i, i + 4);
     
     html += '<div class="print-page">';
     html += '<div class="page-header">名片册系统 - ' + new Date().toLocaleDateString() + '</div>';
     html += '<div class="cards-row">';
     
     rowCards.forEach(card => {
         html += generateSingleCardHTML(card);
     });
     
     html += '</div>';
     html += '<div class="page-footer">第' + (Math.floor(i/4) + 1) + '页</div>';
     html += '</div>';
     
     // 每5行分页
     if ((i/4 + 1) % 5 === 0 && i + 4 < cardsData.length) {
         html += '<div class="page-break"></div>';
     }
 }
 
 return html;
}

//生成单张名片HTML
function generateSingleCardHTML(card) {
 return `
     <div class="business-card">
         <div class="card-header">
             <h3 class="card-name">${card.name || ''}</h3>
             <div class="card-title">${card.title || ''}</div>
         </div>
         <div class="card-company">
             <strong>${card.organization || ''}</strong>
         </div>
         <div class="card-contact">
             <div class="contact-item">
                 <i class="phone-icon">📞</i>
                 <span>${card.phone || ''}</span>
             </div>
             <div class="contact-item">
                 <i class="email-icon">✉️</i>
                 <span>${card.email || ''}</span>
             </div>
             <div class="contact-item">
                 <i class="address-icon">📍</i>
                 <span>${card.address || ''}</span>
             </div>
         </div>
         <div class="card-gender">${card.gender || ''}</div>
     </div>
 `;
}

//打印样式CSS函数
function getPrintCSS() {
    return `
        @page {
            size: A4;
            margin: 15mm;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #333;
            background: white;
        }
        
        .print-content {
            width: 100%;
        }
        
        .print-page {
            width: 100%;
            page-break-after: always;
            position: relative;
            min-height: 250mm;
        }
        
        .print-page:last-child {
            page-break-after: avoid;
        }
        
        .page-header {
            text-align: center;
            font-size: 16px;
            font-weight: bold;
            color: #3a7bd5;
            margin-bottom: 20mm;
            padding-bottom: 5mm;
            border-bottom: 3px solid #3a7bd5;
        }
        
        .page-footer {
            position: absolute;
            bottom: 5mm;
            right: 0;
            font-size: 10px;
            color: #999;
        }
        
        .cards-row {
            display: flex;
            gap: 5mm;
            justify-content: space-between;
            margin-bottom: 8mm;
        }
        
        .business-card {
            width: 85mm;
            height: 54mm;
            border: 2px solid #3a7bd5;
            border-radius: 8px;
            padding: 6mm;
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            position: relative;
            overflow: hidden;
            break-inside: avoid;
        }
        
        .card-decoration-top {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(90deg, #3a7bd5, #00d2ff);
        }
        
        .card-decoration-bottom {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 2px;
            background: linear-gradient(90deg, #e2e8f0, #3a7bd5, #e2e8f0);
        }
        
        .card-header {
            margin-bottom: 4mm;
            border-bottom: 1px solid #e0e0e0;
            padding-bottom: 2mm;
        }
        
        .card-name {
            font-size: 14px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 1mm;
        }
        
        .card-title {
            font-size: 10px;
            color: #7f8c8d;
            font-style: italic;
        }
        
        .card-company {
            font-size: 11px;
            color: #3a7bd5;
            font-weight: 600;
            margin-bottom: 3mm;
        }
        
        .card-contact {
            font-size: 9px;
            line-height: 1.3;
        }
        
        .contact-item {
            display: flex;
            align-items: center;
            margin-bottom: 1mm;
            gap: 2mm;
        }
        
        .contact-item i {
            width: 3mm;
            font-size: 8px;
        }
        
        .card-gender {
            position: absolute;
            top: 3mm;
            right: 3mm;
            font-size: 8px;
            color: #95a5a6;
            background: #ecf0f1;
            padding: 1px 2mm;
            border-radius: 2mm;
        }
        
        .page-break {
            page-break-before: always;
        }
        
        @media print {
            body * {
                visibility: hidden;
            }
            .print-content, .print-content * {
                visibility: visible;
            }
            .print-content {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
        }
    `;
}


//确保获取名片数据的函数存在
if (typeof getCardDataForPrint === 'undefined') {
    async function getCardDataForPrint(cardId) {
        try {
            const response = await fetch('BusinessCardServlet?action=getCardById&cardId=' + cardId);
            if (!response.ok) {
                throw new Error('获取名片数据失败');
            }
            return await response.json();
        } catch (error) {
            console.error('获取名片' + cardId + '失败:', error);
            return null;
        }
    }
}


//确保有hasPermission函数的定义
if (typeof hasPermission === 'undefined') {
 function hasPermission(permissionName) {
     // 管理员拥有所有权限
     if (currentUserType === 'ADMIN') {
         return true;
     }
     
     // 如果权限系统已加载
     if (typeof currentUserPermissions !== 'undefined' && currentUserPermissions) {
         return currentUserPermissions[permissionName] === true;
     }
     
     // 默认权限（如果权限系统未加载）
     const defaultPermissions = {
         'create_card': true,
         'edit_card': true,
         'delete_card': true,
         'create_folder': true,
         'import_export': true,
         'search_replace': true,
         'print': true,
         'manage_users': false,
         'manage_permissions': false
     };
     
     return defaultPermissions[permissionName] || false;
 }
}

//确保有formatBackendDate函数
if (typeof formatBackendDate === 'undefined') {
 function formatBackendDate(dateValue) {
     if (!dateValue) return '未知';
     
     try {
         // 如果是对象格式的日期时间
         if (typeof dateValue === 'object' && dateValue.date && dateValue.time) {
             const year = dateValue.date.year;
             const month = String(dateValue.date.month).padStart(2, '0');
             const day = String(dateValue.date.day).padStart(2, '0');
             const hour = String(dateValue.time.hour).padStart(2, '0');
             const minute = String(dateValue.time.minute).padStart(2, '0');
             
             return `${year}-${month}-${day} ${hour}:${minute}`;
         }
         
         // 如果是字符串格式
         if (typeof dateValue === 'string') {
             const date = new Date(dateValue);
             if (!isNaN(date.getTime())) {
                 return date.toLocaleString('zh-CN', {
                     year: 'numeric',
                     month: '2-digit',
                     day: '2-digit',
                     hour: '2-digit',
                     minute: '2-digit'
                 });
             }
         }
         
         return String(dateValue);
     } catch (error) {
         console.warn('日期格式化失败:', error, dateValue);
         return '格式错误';
     }
 }
}

//修复 executePrint 函数（如果需要的话）
function executePrint(cardsData) {
 // 创建打印内容
 const printContent = generatePrintHTML(cardsData);
 
 // 创建新窗口
 const printWindow = window.open('', '_blank', 'width=800,height=600');
 
 if (!printWindow) {
     showMessage('无法打开打印窗口，请检查浏览器设置', 'error');
     return;
 }
 
 printWindow.document.write(printContent);
 printWindow.document.close();
 
 // 等待内容加载完成后打印
 printWindow.onload = function() {
     setTimeout(() => {
         printWindow.focus();
         printWindow.print();
         
         // 打印完成后关闭窗口
         setTimeout(() => {
             printWindow.close();
         }, 1000);
     }, 500);
 };
 
 // 显示打印状态
 showMessage('打印窗口已打开，请在弹出窗口中完成打印', 'success');
}

//生成打印HTML的辅助函数
function generatePrintHTML(cardsData, isPreview = false) {
 return `
     <!DOCTYPE html>
     <html>
     <head>
         <meta charset="UTF-8">
         <title>名片打印 - ${cardsData.length}张</title>
         <style>
             ${getPrintCSS()}
         </style>
     </head>
     <body>
         <div class="print-content">
             ${generateCardsPrintHTML(cardsData)}
         </div>
         ${isPreview ? '' : '<script>window.onload = () => { setTimeout(() => window.print(), 500); };</script>'}
     </body>
     </html>
 `;
}

//生成名片打印HTML内容的辅助函数
function generateCardsPrintHTML(cardsData) {
 let html = '';
 
 // 每4张名片一行，最多5行一页
 for (let i = 0; i < cardsData.length; i += 20) {
     const pageCards = cardsData.slice(i, i + 20);
     const pageNum = Math.floor(i / 20) + 1;
     const totalPages = Math.ceil(cardsData.length / 20);
     
     html += '<div class="print-page">';
     html += `<div class="page-header">名片册系统 - ${new Date().toLocaleDateString()} - 第${pageNum}页/共${totalPages}页</div>`;
     
     // 每4张名片一行
     for (let j = 0; j < pageCards.length; j += 4) {
         const rowCards = pageCards.slice(j, j + 4);
         html += '<div class="cards-row">';
         
         rowCards.forEach(card => {
             html += generateSingleCardHTML(card);
         });
         
         html += '</div>';
     }
     
     html += `<div class="page-footer">第${pageNum}页 - 共${cardsData.length}张名片</div>`;
     html += '</div>';
     
     // 分页
     if (i + 20 < cardsData.length) {
         html += '<div class="page-break"></div>';
     }
 }
 
 return html;
}

//生成单张名片HTML的辅助函数
function generateSingleCardHTML(card) {
 return `
     <div class="business-card">
         <div class="card-decoration-top"></div>
         
         <div class="card-header">
             <h3 class="card-name">${card.name || ''}</h3>
             <div class="card-title">${card.title || ''}</div>
         </div>
         
         <div class="card-company">
             <strong>${card.organization || ''}</strong>
         </div>
         
         <div class="card-contact">
             <div class="contact-item">
                 <i class="phone-icon">📞</i>
                 <span>${card.phone || ''}</span>
             </div>
             <div class="contact-item">
                 <i class="email-icon">✉️</i>
                 <span>${card.email || ''}</span>
             </div>
             <div class="contact-item">
                 <i class="address-icon">📍</i>
                 <span>${card.address || ''}</span>
             </div>
         </div>
         
         <div class="card-gender">${card.gender || ''}</div>
         <div class="card-decoration-bottom"></div>
     </div>
 `;
}
